﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using OA.Manager;
using OA.Model;
using OA.Utility;
using System.Data;

namespace OA.Bll
{
    public class DictionaryInfoPresenter
    {
        private readonly DictionaryManager _dtm = new DictionaryManager();
        private readonly ManagerParent<DictionaryInfo> _manager = new ManagerParent<DictionaryInfo>();

        public string GetDictionaryInfoAll(int id, bool showchild)
        {
            string sql = string.Empty;
            //string sql = "typeId='" + id + "' and ParentId='";
            if (showchild)
                sql = "typeId='" + id + "'";
            else
                sql = "typeId='" + id + "' and ParentId is null ";
            List<DictionaryInfo> list = _dtm.GetDictionaryInfoAll(sql);
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            foreach (DictionaryInfo dictionaryInfo in list)
            {
                sb.Append("{");
                if (dictionaryInfo != null)
                    sb.Append(string.Format("\"id\": \"{0}\", \"text\": \"{1}\"",
                                            dictionaryInfo.Id.ToString(CultureInfo.InvariantCulture),
                                            dictionaryInfo.ItemValue));
                sb.Append("},");
            }
            sb.Remove(sb.ToString().Length - 1, 1);
            sb.Append("]");
            return sb.ToString();
        }

        public string GetDictionaryInfoAll(int id, int parentId)
        {
            List<DictionaryInfo> list = _dtm.GetDictionaryInfoAll(id, parentId);
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            foreach (DictionaryInfo dictionaryInfo in list)
            {
                sb.Append("{");
                if (dictionaryInfo != null)
                    sb.Append(string.Format("\"id\": \"{0}\", \"text\": \"{1}\"",
                                            dictionaryInfo.Id.ToString(CultureInfo.InvariantCulture),
                                            dictionaryInfo.ItemValue));
                sb.Append("},");
            }
            sb.Remove(sb.ToString().Length - 1, 1);
            sb.Append("]");
            return sb.ToString();
        }


        public string Paged(JsonReq req)
        {
            int pageIndex = Convert.ToInt32(req["page"]);
            int pageSize = Convert.ToInt32(req["rows"]);
            //DictionaryManager manager = new DictionaryManager();
            int total = 0;
            DataTable table = _dtm.GetPaged(pageIndex, pageSize, ref total);
            // int total = manager.GetDictionaryTypeTotal();
            string result = JsonHelper.OnDataGrid(table, total);
            // JsonHelper.ListToGridJson<DictionaryInfo>(list, total);
            return result;
        }

        public string Search(JsonReq req)
        {
            int pageIndex = Convert.ToInt32(req["page"]);
            int pageSize = Convert.ToInt32(req["rows"]);
            int total = 0;
            DictionaryInfo info = JsonHelper.JsonDeserialize<DictionaryInfo>(req.Options);
            DataTable dt = _dtm.GetSearchPaged(info, pageIndex, pageSize, ref total);
            return JsonHelper.OnDataGrid(dt, total);
            //  return JsonHelper.ListToGridJson<DictionaryInfo>(list, total);
        }

        public string Add(JsonReq req)
        {
            //DictionaryInfo info = new DictionaryInfo
            //{
            //    ItemKey = req["ItemKey"],
            //    Description = req["Description"],
            //    ItemValue = req["ItemValue"],
            //    TypeId = req["TypeId"].ToInt32(),
            //    ParentId = req["ParentId"].ToInt32(),
            //    OrderId = req["OrderId"].ToInt32()
            //};

            DictionaryInfo info = JsonHelper.JsonDeserialize<DictionaryInfo>(req.Options);
            bool bl = _dtm.InsertDictionaryInfo(info);
            return "{ \"flag\":\"" + bl.ToString(CultureInfo.InvariantCulture) + "\",\"msg\":\"" +
                   (bl ? "添加成功!" : "添加失败!") + "\"}";
        }

        public string Update(JsonReq req)
        {
            DictionaryInfo info = new DictionaryInfo
                                      {
                                          Id = Convert.ToInt32(req["Id"]),
                                          ItemKey = req["ItemKey"],
                                          Description = req["Description"],
                                          ItemValue = req["ItemValue"],
                                          TypeId = req["TypeId"].ToInt32(),
                                          ParentId = req["ParentId"].ToInt32(),
                                          OrderId = req["OrderId"].ToInt32()
                                      };
            bool bl = _dtm.UpdateDictionaryInfo(info,
                                                new List<string>
                                                    {
                                                        "ItemKey",
                                                        "TypeId",
                                                        "ItemValue",
                                                        "Description",
                                                        "ParentId",
                                                        "OrderID"
                                                    });
            return "{ \"flag\":\"" + bl.ToString(CultureInfo.InvariantCulture) + "\",\"msg\":\"" +
                   (bl ? "修改成功" : "修改失败") + "\"}";
        }

        public string Delete(JsonReq req)
        {
            DictionaryInfo info = new DictionaryInfo
                                      {
                                          Id = Convert.ToInt32(req["Id"]),
                                      };
            bool bl = _dtm.DeleteDictionaryInfo(info);
            return "{ \"flag\":\"" + bl.ToString(CultureInfo.InvariantCulture) + "\",\"msg\":\"" +
                   (bl ? "删除成功" : "删除失败") + "\"}";
        }

        public string GetSearchAll(string id)
        {
            List<DictionaryInfo> list = _manager.GetSearchAll(" and  TypeId='" + id + "' and ParentId is null");// 将ParentId修改为TypeID,实际是使用TypeID获取第一次数据
            List<TreeModel> treeList = list.Select(a => ConverToTreeModel(a)).ToList();
            if (treeList.Count > 0)
                treeList[0].State = "open";
            string result = JsonHelper.GetTreeJson(treeList, "Id", "Text", "Children", "", "Checked", "State");
            return result;
        }
        private TreeModel ConverToTreeModel(DictionaryInfo info)
        {
            TreeModel tree = new TreeModel { Id = info.Id, Text = info.ItemValue };

            List<DictionaryInfo> list = _manager.GetSearchAll("and ParentId='" + info.Id + "'");
            tree.Children = list.Select(a => ConverToTreeModel(a)).ToList();
            return tree;
        }
    }
}
